package base

import (
	"jiance_server/log"
	"net/http"

	dybase "github.com/cdongyang/library/web/handler/base"
)

var NewHandler = dybase.NewHandler

type Logger struct {
}

var defaultLogger Logger

func (Logger) BeforeServeHTTP(w http.ResponseWriter, r *http.Request) bool {
	log.Debugln(r.Method, r.URL.Path)
	bs, err := dybase.CopyRequestBody(r)
	if err != nil {
		log.Errorln("filter by Logger:", err)
		return true
	}
	log.Debugf("request: %s\n", bs)
	return false
}

func (Logger) AfterServeHTTP(w http.ResponseWriter, r *http.Request) bool {
	log.Debugf("response: %s\n", w.(*dybase.ResponseWriter).Buffer.String())
	return false
}

func NewHandlerWithMethods(handleFunc func(w http.ResponseWriter, r *http.Request), methods ...string) dybase.BaseHandler {
	return dybase.NewHandler(handleFunc, dybase.NewMethodFilter(methods), defaultLogger)
}
